package com.itheima.tlias84.Interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.utils.JwtUtil;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录拦截器：拦截器由Spring提供
 * 实现拦截器接口：HandlerInterceptor接口(有三个默认接口,重写preHandle)
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    EmpMapper empMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始执行http请求拦截");
        //放行登录接口，不能拦截登录-->获取url来判断
        /*
        在WebMvcConfig中添加了拦截路径，且排除了登录路径，所以此处注掉
         */
//        String uri = request.getRequestURI();
//        if (uri.contains("login")){
//            return true;
//        }
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断是否有token：有token，继续执行，没有token，拦截-先登录获取token
        if (Objects.isNull(token)){
            //设置编码格式
            writeErrorResponse(response,"请先登录");
            return false;
        }
        log.info("存在token继续执行-->下一步验证token");
        //使用jwt验证token+捕获异常：token不合法/失效
        try {
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            if (Objects.isNull(emp) || !emp.getPassword().equals(jsonObject.getString("password"))){
                writeErrorResponse(response,"用户不存在");
                return false;
            }
        }catch (Exception e){
            writeErrorResponse(response, "token无效，请重新登录");
            log.info("token无效，请重新登录");
            return false;
        }

        //过滤琏对象执行完过滤完后，要放行http请求-->把Request、Response重新交给controller
        log.info("执行过滤器逻辑完毕");
        return true;
    }


    private static void writeErrorResponse(HttpServletResponse servletResponse, String msg) throws IOException {
        servletResponse.setContentType("application/json;charset=utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        //设置响应状态码:401（不能返回200）-->未授权-->直接跳转登录页面（真高级）
        servletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
        PrintWriter writer = servletResponse.getWriter();
        ResultUtil fail = ResultUtil.fail(msg);
        log.info("拦截成功，请先登录！");
        //使用fastjson 转成JSON格式
        String json = JSONObject.toJSONString(fail);
        writer.write(json);
    }
}
